package lib;

import java.io.*;
import java.net.MalformedURLException;
import java.util.*;

import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import com.thoughtworks.xstream.*;
/**
 * To get the detail page of a book even the page does not contain "details"
 * 
 * @author smy
 */
public class GetBookAvailability {
	private ArrayList<Book> books=new ArrayList <Book>();
	private static final String preURL = "http://202.119.47.8:8080/opac/item.php?marc_no=";
    private XStream xs=new XStream();
    private String path;
    private int no;
    public static void main(String[] args){
    	/*if(args.length!=2){
    		System.err.println("Invaild input!");
    		System.exit(1);
    	}*/
    	GetBookAvailability gba=new GetBookAvailability("d:/BSWD/test.xml",3);
    	try {
			gba.DoWork();
		} catch (Exception ex) {
			System.err.println("An error occured");
			System.err.println(ex.getMessage());
			System.exit(2);
		}
    }
	@SuppressWarnings("unchecked")
	public GetBookAvailability(String source,int i){
		try {
			FileInputStream fis=new FileInputStream(source);
			books=(ArrayList<Book>) xs.fromXML(fis);
			this.no=i;
			this.path=source;
		} catch (FileNotFoundException e) {
			System.err.println("File not found!");
			System.exit(1);
		}
	}
	public void DoWork() throws FailingHttpStatusCodeException,
			MalformedURLException, IOException {
		long aaa=System.currentTimeMillis();
		WebClient wc = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
		wc.setCssEnabled(false);
		wc.setJavaScriptEnabled(false);
		HtmlPage wp=wc.getPage(preURL + books.get(no).getmarcno());
		books.get(no).clear();
		List<HtmlElement> list = wp.getElementsByTagName("table");
		HtmlTable table = (HtmlTable) list.get(0);
		for (int j = 1; j < table.getRowCount(); j++) {
			HtmlTableRow htr = table.getRow(j);
			String location = "";
			String avail = "";
			location=htr.getCell(4).asText();
			avail=htr.getCell(5).asText();
			books.get(no).setavailability(avail);
			books.get(no).setlocation(location);
		}
       FileOutputStream fos=new FileOutputStream(path);
       xs.toXML(books,fos);
       System.out.println("Done in "+(System.currentTimeMillis()-aaa)+" ms.");
	}
}
